package cn.tedu.mall.order.consumer;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.front.service.IFrontSkuService;
import cn.tedu.mall.order.mappers.OrderMapper;
import cn.tedu.mall.pojo.order.model.OmsOrder;
import cn.tedu.mall.seckill.service.ISeckillSkuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RocketMQMessageListener(
        topic = "csmall-order-delay-topic",
        consumerGroup = "order-delay-group",
        selectorExpression = "*"
)
public class OrderDelayConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private OrderMapper orderMapper;
    @DubboReference
    private IFrontSkuService frontSkuService;
    @DubboReference
    private ISeckillSkuService seckillSkuService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void onMessage(MessageExt message) {
        String tags = message.getTags();
        if (tags.equals("localDelay")) {
            String sn = new String(message.getBody());
            // 消息体中的内容就是订单编号,利用订单编号,查询订单是否存在OmsOrder
            OmsOrder order = orderMapper.selectOrderBySn(sn);
            // 判断订单状态是否state=0未支付
            if (order != null && order.getState() == 0){
                //面试题:订单库存是下单时候减,还是支付的时候减(一般是前者，下单时候减)
                //如果是直接改成1（超时未支付）
                //update oms_order set state=1 where sn=#{sn}
                orderMapper.shutDownOrderBySn(sn);
                //回退库存
                frontSkuService.returnStock(sn);
            }
        } else if (tags.equals("seckillDelay")) {
            // 消息体中，逗号前面的是sn，逗号后面的是skuId
            String msgBody = new String(message.getBody());
            String sn = msgBody.split(",")[0];
            String skuId = msgBody.split(",")[1];
            // 查询订单是否存在OmsOrder
            OmsOrder order = orderMapper.selectOrderBySn(sn);
            // 判断订单状态是否state=0,未支付
            if (order != null && order.getState() == 0){
                orderMapper.shutDownOrderBySn(sn);
                // 回退库存
                seckillSkuService.returnStock(sn);
                // 清除重复秒杀redis中的缓存
                Long userId = order.getUserId();
                String repeatKey = "seckill:" + userId + ":" + skuId;
                stringRedisTemplate.delete(repeatKey);
            }
        } else {
            throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "未知标签：" + tags);
        }
    }
}
